package request

import (
	"aixinge/api/model/common"
	"aixinge/api/model/message"
	"aixinge/utils/snowflake"
	"errors"
	"github.com/flosch/pongo2/v6"
)

type ApiParams struct {
	TemplateId  snowflake.ID       `json:"templateId" swaggertype:"string"` // 模板 ID
	Type        message.MsgType    `json:"type"`                            // 消息类型(枚举)
	Content     common.MapConfig   `json:"content"`                         // 内容 Map 配置
	Attachments common.Attachments `json:"attachments"`                     // 附件 JSON
}

func (a *ApiParams) GetContext() pongo2.Context {
	ctx := make(pongo2.Context)
	for k, v := range a.Content {
		ctx[k] = v
	}
	return ctx
}

func (a *ApiParams) Render(text string, context pongo2.Context) (string, error) {
	tpl, err := pongo2.FromString(text)
	if err != nil {
		return text, err
	}
	return tpl.Execute(context)
}

func (a *ApiParams) ContentString(key string) (result string) {
	value := a.Content[key]
	if value != nil {
		result = value.(string)
	}
	return result
}

func (a *ApiParams) ContentStringSlice(key string) (result []string, err error) {
	value := a.Content[key]
	if value == nil {
		return result, err
	}
	return getSlice(value)
}

func getSlice(value interface{}) (result []string, err error) {
	switch value.(type) {
	case []interface{}:
		for _, val := range value.([]interface{}) {
			result = append(result, val.(string))
		}
	case interface{}:
		result = append(result, value.(string))
	default:
		err = errors.New("content param type is error")
		break
	}
	return result, err
}
